<?php
	session_start();
	include('include/db_connect.php');
	include('include/header.php');
	include('include/menu.php');
?>
<script type=text/javascript>
	function delayer() {
	    window.location = "index.php"
	}
</script>
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
<?php
	//include('include/db_connect.php');
	$arrayRegisterFields = array("Persoonlijke gegevens", "*Voornaam", "Tussenvoegsel", "*Achternaam", "*E-mailadres", 
	                             "*Straat", "*Huisnummer", "Huisnummertoevoeging", "*Postcode", "*Woonplaats", "Inloggegevens", 
	                             "*Gebruikersnaam", "*Wachtwoord", "*Nog een keer wachtwoord");
	$showForm = true;
	$checkForm = false;
	if(isset($_POST['insert'])) {
		$showForm = false;
		$insertForm = true;
	} else {
		$insertForm = false;
	}
	$arrayWrongData = array();
	$usernameQuery = mysql_query("SELECT `gebruikers_naam` FROM USERNAME");
	if(!$usernameQuery) {
		die("Username query failed. Please try again later.");
	}
	if(mysql_fetch_assoc($usernameQuery) != false) {
		$arrayUsername = mysql_fetch_assoc($usernameQuery);
	} else {
		$arrayUsername = array();
	}
	$welcomequery = mysql_query("SELECT omschrijving FROM `PAGINAOMSCHRIJVING` WHERE naam_pagina = 'register.php#welcome'");		   
	$welcomeres = mysql_fetch_assoc($welcomequery);
	$welcomeText = $welcomeres['omschrijving'];
	
	$verifyquery = mysql_query("SELECT omschrijving FROM `PAGINAOMSCHRIJVING` WHERE naam_pagina = 'register.php#verify'");		   
	$verifyres = mysql_fetch_assoc($welcomequery);
	$verifyText = $verifyres['omschrijving'];
	
	$insertquery = mysql_query("SELECT omschrijving FROM `PAGINAOMSCHRIJVING` WHERE naam_pagina = 'register.php#insert'");		   
	$insertres = mysql_fetch_assoc($insertquery);
	$insertText = $insertres['omschrijving'];
	
	
	//checking if user clicked on de register button
	if(!isset($_SESSION['logged'])) {
		if(isset($_POST) && !empty($_POST) && $checkForm == false && $insertForm == false) {
			//and now check if everything is filled in correctly
			foreach($arrayRegisterFields as $key) {
				$key = strtolower($key);
				if($key != "persoonlijke gegevens" && $key != "inloggegevens") {
					$key = str_replace(' ', '_', $key);
					
					//krijg er problemen mee met '*nog een keer wachtwoord', super raar... (Jeroen)
					if($key != "*nog_een_keer_wachtwoord") {
						$_POST[$key] = trim($_POST[$key]);
					}
					if(!empty($_POST[$key])) {
						if($key == "*voornaam" || $key == "*achternaam" || $key == "*straat") {
							if(preg_match("/[^a-zA-Z\s]/", $_POST[$key])) {
								$arrayWrongData[count($arrayWrongData)] = $key;
								echo $_POST[$key];
							}
						} else if($key == "*e-mailadres") {
							if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', 
							               $_POST[$key])) {
								$arrayWrongData[count($arrayWrongData)] = $key;
								echo $_POST[$key];
							}
						} else if($key == "*huisnummer") {
							if(!is_numeric($_POST[$key])) {
								$arrayWrongData[count($arrayWrongData)] = $key;
							}
						} else if($key == "*postcode") {
							$_POST[$key] = str_replace(' ', '', $_POST[$key]);
							if(strlen($_POST[$key]) != 6) {
								//er moet nog een extra regex voor postcode!
								//maar ik heb geen zin meer! :P (Jeroen)
								$arrayWrongData[count($arrayWrongData)] = $key;
							}
						} else if($key == "*gebruikersnaam") {
							if(in_array($_POST[$key], $arrayUsername)) {
								$arrayWrongData[count($arrayWrongData)] = $key;
							}
						} else if($key == '*wachtwoord' || $key == '*nog_een_keer_wachtwoord') {
							if($_POST["*wachtwoord"] != $_POST["*nog_een_keer_wachtwoord"]) {
								$arrayWrongData[count($arrayWrongData)] = "*wachtwoord";
								$arrayWrongData[count($arrayWrongData)] = "*nog_een_keer_wachtwoord";
							}
						}
					} else if($key != "tussenvoegsel" && $key != "huisnummertoevoeging") {
						$arrayWrongData[count($arrayWrongData)] = $key;
					}
				}
			} //end validation
			if(count($arrayWrongData) == 0) {
				$showForm = false;
				$checkForm = true;
			}
		} else if($insertForm == true) {
			$encryptedPasswd = md5($_POST['*wachtwoord']);
			//this block is only executed if user has filled everything filled in correctly and checked his/her data
			$insertNewUsernameQuery = mysql_query("INSERT INTO USERNAME (`gebruikers_naam`, `wachtwoord`) ".
			                                      "VALUES ('".$_POST['*gebruikersnaam']."', '".$encryptedPasswd."')");
			if(!$insertNewUsernameQuery) {
				die("Query failed. Please try again later. ".mysql_error());
			}
			$insertNewUserAddressQuery = mysql_query("INSERT INTO ADRES (`postcode`, `straat_naam`, `huis_nummer`, `toevoeging`, `woonplaats`) ".
			                                         "VALUES ('".$_POST['*postcode']."', '".$_POST['*straat']."', ".
			                                         intval($_POST['*huisnummer']).", '".$_POST['huisnummertoevoeging']."', '".
			                                         $_POST['*woonplaats']."')");
			if(!$insertNewUserAddressQuery) {
				die("Query failed. Please try again later. ".mysql_error());
			}
			$idUsernameQuery = mysql_query("SELECT `idUSERNAME` FROM USERNAME ".
			                               "WHERE `gebruikers_naam` = '".$_POST['*gebruikersnaam']."'");
			if(!$idUsernameQuery) {
				die("Query failed. Please try again later. ".mysql_error());
			}                         
			$idAdresQuery = mysql_query("SELECT `idADRES` FROM ADRES WHERE `postcode` = '".
			                             str_replace(' ', '', $_POST['*postcode'])."' AND `straat_naam` = '".
			                             $_POST['*straat']."' AND `huis_nummer` = ".intval($_POST['*huisnummer']));
			if(!$idAdresQuery) {
				die("Query failed. Please try again later. ".mysql_error());
			}
			$idUsername = mysql_result($idUsernameQuery, 0);
			$idAdres = mysql_result($idAdresQuery, 0);
			$insertNewUserdataQuery = mysql_query("INSERT INTO USER_DATA (`USERNAME_idUSERNAME`, `ADRES_idADRES`, `voornaam`, ".
			                                      "`achternaam`, `tussenvoegsel`, `email`) ".
			                                      "VALUES(".$idUsername.", ".$idAdres.", '".$_POST['*voornaam']."', '".
			                                      $_POST['*achternaam']."', '".$_POST['tussenvoegsel']."', '".$_POST['*e-mailadres']."')");
	   		if(!$insertNewUserdataQuery) {
				die("Query failed. Please try again later. ".mysql_error());
			}
			$showForm = false;
			$checkForm = false;
		}
	} else {
		//als je bent ingelogd hoef je natuurlijk niet meer te registeren!
		//dat is hierdoor dan ook onmogelijk gemaakt!
		header('Location: index.php');
	}
	echo "<div id='main_content'>";
	echo "<div id='super_main_content'>";
	if($showForm == true) {
		echo $welcomeText;
		echo "<form action='register.php' method='post'><table>";
		foreach($arrayRegisterFields as $key) {
			//uitzonderingen stuff
			if($key == "*Wachtwoord" || $key == "*Nog een keer wachtwoord") {
				$type = "password";
			} else {
				$type = "text";
			}
			if(in_array($key, $arrayWrongData)) {
				$tdClass = " class='wrong'";
			} else {
				$tdClass = "";
			}
			
			if($key == "Persoonlijke gegevens" || $key == "Inloggegevens") {
				echo "<tr><th>".$key."</th></tr>\n";
			} else {
				echo "<tr><td".$tdClass.">".$key."</td>\n";
				echo "<td><input type=".$type." name='".strtolower($key)."'</td></tr>\n";
			}					
		}
		?>
		<?php
		echo "<tr><td></td><td></td><td><input type='button'". 
		                                "value='Registreer!' onClick='this.form.submit()'></td></tr>";
		echo "</table></form>";
	} else if($checkForm == true){
		//laat een 'check je gegevens scherm zien'
		echo $verifyText;
		echo "<table>";
		echo "<form action='register.php' method='post'>";
		foreach($arrayRegisterFields as $key) {
			//uitzonderingen stuff
			if($key == "*Wachtwoord" || $key == "*Nog een keer wachtwoord") {
				$type = "password";
			} else {
				$type = "text";
			}		
			if($key == "Persoonlijke gegevens" || $key == "Inloggegevens") {
				echo "<tr><th>".$key."</th></tr>";
			} else {
				$fieldName = str_replace('*', '', $key);
				$key = strtolower(str_replace(' ', '_', $key));
	
				echo "<tr><td>".$fieldName."</td>";
				echo "<td><input type='".$type."' name='".strtolower($key)."' value='".$_POST[$key]."'></td></tr>";
			}					
		}
		echo "</table>";
		echo "<input type='hidden' name='insert' value='insert'><input type='button' value='Klopt niet. Ga terug' onClick='history.go(-1)'>".
		     "<input type='button' value='Registreer!' onClick='form.submit()'></form>";
	} else if($insertForm == true) {
		echo $insertText;
		echo "<script type='text/javascript'>setTimeout('delayer()', 5000)</script>";
	}
	echo "<br>";
	echo "</div>";
	echo "</div>";
	echo "<div class='clearthis'></div>";
	include('include/footer.php');
?>